package services

import (
	"hg/enmu"
	"hg/models"
	"hg/pkg/database"
	"hg/pkg/middleware"
	"hg/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)


// 登录函数
func LoginPostService(c *gin.Context) {
	user := new(models.Userinfo)
	resp := models.GetDefaultResp()
	if err := c.ShouldBindJSON(&user); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}	
	if ok, token := login(user.Username, user.Password); ok && token != "" {
		utils.SetCookie(c,token)
		resp.Data = token
		c.JSON(http.StatusOK, resp)
	} else {
		resp.Code, resp.Msg = enmu.BAD_LOGIN_INFO_CODE, enmu.BAD_LOGIN_INFO_MSG
		c.JSON(http.StatusBadRequest, resp)
	}
}

func login(username, password string) (bool, string) {
	user, err := database.GetUserinfoByUsername(username)
	if err != nil {
		logrus.Error("获取用户信息失败:", err)
		return false, ""
	}
	hashedPassword := utils.HashPassword(password, username)
	if hashedPassword != user.Password {
		return false, ""
	}
	token, err := middleware.CreateToken(user)
	if err != nil {
		logrus.Errorln("Token签名失败:", err)
		return false, ""
	}
	return true, token
}
